import type { AccountInfo } from '@/apis/model/auth'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAppStore = defineStore(
  storesKey.app,
  () => {
    const token = ref('')
    const router = useRouter()
    const accountInfo = ref<AccountInfo>()
    const saveToken = (newToken: string) => {
      localStorage.setItem(WEB_AUTH_ADMIN_TOKEN, newToken)
      token.value = newToken
    }
    const clearToken = () => {
      localStorage.removeItem(WEB_AUTH_ADMIN_TOKEN)
      token.value = ''
    }
    const saveAccountInfo = (value: any) => {
      accountInfo.value = value
    }
    const clearLoginInfoAction = () => {
      clearToken()
      accountInfo.value = undefined
      localStorage.removeItem(storesKey.app)
      router.replace('/sign-in')
    }
    const logout = () => {
      clearToken()
      router.replace('/sign-in')
    }
    return {
      token,
      saveToken,
      logout,
      accountInfo,
      saveAccountInfo,
      clearLoginInfoAction
    }
  },
  {
    persist: true
  }
)
